/*
 * 用于常见的 query 参数获取
 * */
function getQueryVariable(variable) {
  const query = window.location.search.substring(1)
  const vars = query.split('&')
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=')
    if (pair[0] === variable) {
      return pair[1]
    }
  }
  return false
}

/**
 * 常规图片导入
 */
export function getImageUrl(name, type = '.png') {
  return new URL(`../assets/${name}${type}`, import.meta.url).href
}

/*
 * 活动专用
 * */
function getToken() {
  return decodeURIComponent(window.location.hash.split('?')[1].replace('token=', '')).replace(/\s/g, '+')
}
/**
 * 防抖函数
 * @param {*} fn  回调函数
 * @param {*} delay  延迟时间
 * @returns
 */
export function debounce(fn, delay = 500) {
  let timer
  return function () {
    const that = this
    const args = arguments
    if (timer) clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}

function getQueryParams(key) {
  const obj = {}
  decodeURI(window.location.href)
    ?.split('?')[1]
    ?.split('&')
    .forEach((item) => {
      const arr = item?.split('=')
      arr.shift()
      // 当有路由时, 将路由相关当去除
      arr[arr.length - 1] = arr[arr.length - 1].split('#')[0]
      // 解决token中有 = 号的问题
      obj[item?.split('=')[0]] = arr?.join('=')
    })
  return obj[key]
}

/**
 * 调用IOS | android API接口方法
 * 消息传送
 * type: 执行操作类型
 *     src/common/ConstantPool.js IOS_COMMAND 查看所有 type
 *     eg : sendMessage(IOS_COMMAND.CLOSE)
 * data: 所需要的参数
 *     和IOS安卓协商参数
 * */
function sendMessage(type, params = {}) {
  const materials = { type }
  const u = navigator.userAgent
  const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
  if (isiOS) {
    materials.params = params
    window.webkit.messageHandlers.common.postMessage(JSON.stringify(materials))
  } else if (isAndroid) {
    materials.data = params
    window.bridge.postMessage(JSON.stringify(materials))
  }
}

export { getToken, getQueryVariable, getQueryParams, sendMessage }
